<template>
  <!--banner轮播-->
  <div class="swiper-container" ref="Swiper">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="item in swiperData" :key="item.id">
        <img :src="item.imgUrl" />
      </div>
    </div>
    <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>

    <!-- 如果需要导航按钮 -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
  </div>
</template>

<script>
import Swiper from "swiper";
import "swiper/css/swiper.min.css";
export default {
  name: "Swiper",
  props: ["swiperData"],
  watch: {
    //监听swiperData的改变
    swiperData: {
      //立即监听
      immediate: true,
      handler() {
        //因为实例化swiper是操作最新的DOM,所以需要写在$nextTick()回调函数中
        //$nextTick将回调延迟到下次 DOM 更新循环之后执行
        this.$nextTick(() => {
          // 判断swiperData 如果初始化的时候是没有数据的不需要new Swiper 就直接return退出
          if (!this.swiperData.length) return;
          new Swiper(this.$refs.Swiper, {
            direction: "horizontal", // 垂直切换选项
            loop: true, // 循环模式选项

            // 如果需要分页器
            pagination: {
              el: ".swiper-pagination",
            },

            // 如果需要前进后退按钮
            navigation: {
              nextEl: ".swiper-button-next",
              prevEl: ".swiper-button-prev",
            },
            //开启自动轮播
            autoplay: true,
          });
        });
      },
    },
  },
};
</script>

<style></style>
